package cs575.common;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

/**
 * Connection Thread that is created when a new client connects to the server
 * 
 */
public class ConnectionThread extends Thread {
	private Socket clientSocket;
	private Parser parser;

	/**
	 * Constructor - server
	 * 
	 * @param socket
	 *            - Connected Socket
	 */
	public ConnectionThread(Socket socket, Parser parser) {
		clientSocket = socket;
		this.parser = parser;
	}

	/**
	 * Constructor - client
	 * 
	 * @param ip
	 *            - IP of server
	 * @param port
	 *            - Port of server
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public ConnectionThread(String ip, int port) throws IOException,
			UnknownHostException {
		clientSocket = new Socket(ip, port);
	}

	/**
	 * Thread run function, uses a switch statement
	 */
	public void run() {
		//TODO handle bigger messages
		byte readBuffer[] = new byte[5000];
		int read = 0;

		try {
			InputStream in = clientSocket.getInputStream();

			while (clientSocket.isConnected() && !clientSocket.isClosed()) {
				read = in.read(readBuffer);
				if (read <= 0) {
					break;
				}

				FantasyMessage response = parser.parseMessage(ByteBuffer.wrap(readBuffer));
				
				if(response != null) {
					clientSocket.getOutputStream().write(response.toBytes());
				}
				
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
				}

			}
			clientSocket.close();

		} catch (IOException e) {
			System.out.println("Client I/O Error");
			e.printStackTrace();
		}

	}

}
